/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
//
package controller;

import core.telechargertest;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author phinguyen
 */
public class Servletupload extends HttpServlet {

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        boolean isOk = fileLoad(request, response);
        RequestDispatcher rd;
        if (isOk == true) {
            rd = request.getRequestDispatcher("ServletDetailsOnDecisionAfterUpload");
            telechargertest tcore = new telechargertest();
            try {
                String docid = (String) request.getAttribute("doctypeselectd");
                System.out.println("------------------------------------------docid : " + docid);
                int iddoc = Integer.parseInt(docid);
                String empid = (String) request.getAttribute("empselectd");
                System.out.println("------------------------------------------empid : " + empid);
                int idemp = Integer.parseInt(empid);
                Date date = new Date();
                System.out.println("------------------------------------------idemp : " + idemp);
                String desid = (String) request.getAttribute("decision");
                System.out.println("------------------------------------------desid : " + desid);
                int iddes = Integer.parseInt(desid);
                String title = (String) request.getAttribute("title");
                tcore.saveDocVersion(iddoc, idemp, iddes, title, date, (String) request.getAttribute("url"));
            } catch (NumberFormatException ex) {
                System.out.println("Number format exception : " + ex.getMessage());
            }
        } else {
            
            rd = request.getRequestDispatcher("ServletDetailsOnDecisionAfterUpload");
        }
        System.out.println("decision_txt (servletupload) : " + request.getAttribute("decision"));
        request.setAttribute("decision_txt", request.getAttribute("decision"));
        rd.forward(request,response);
    }

    public boolean fileLoad(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        try {
            boolean ismultipart = ServletFileUpload.isMultipartContent(request);
            System.out.println("ismultipart-----------------------------------------------------------------" + ismultipart);
            request.setCharacterEncoding("UTF-8");

            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu = new ServletFileUpload(factory);

            List<FileItem> fileItems = sfu.parseRequest(request);
            for (int i = 0; i < fileItems.size(); i++) {
                FileItem item = fileItems.get(i);
                if (item.isFormField()) {
                    String fieldname = item.getFieldName();
                    String value = item.getString();
                    request.setAttribute(fieldname, value);
                } else {
                    String url = this.getServletContext().getRealPath("/uploadfile");
                    System.out.println(url + "-----------------------------------------------url");
//                    String fileName = item.getName();
//                    File fileorigine = (File) item;
//                    String urlorigine = fileorigine.getAbsolutePath();
//                    int index = urlorigine.lastIndexOf("\\");
//                    String fileName = urlorigine.substring(index + 1);
                    String filePath = item.getName();
                    int index = filePath.lastIndexOf("\\");
                    String fileName = filePath.substring(index + 1);
                    System.out.println(fileName + "-----------------------------------------------fileName");
                    File newfile = new File(url, fileName);
                    item.write(newfile);
                    String realurl = newfile.getAbsolutePath();
                    System.out.println(realurl + "-----------------------------------------------realUrl");
                    request.setAttribute("url", realurl);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("upload failed");
            return false;
        }
        System.out.println("upload succeed");
        return true;

    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
